package com.feng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.constants.SystemConstants;
import com.feng.domain.dto.AddArticleDto;
import com.feng.domain.dto.AdminUpdateGetArticleDto;
import com.feng.domain.entity.Article;
import com.feng.domain.entity.ArticleTag;
import com.feng.domain.entity.Category;
import com.feng.domain.vo.*;
import com.feng.domain.ResponseResult;
import com.feng.enums.AppHttpCodeEnum;
import com.feng.mapper.ArticleMapper;
import com.feng.mapper.TagMapper;
import com.feng.service.ArticleService;
import com.feng.service.ArticleTagService;
import com.feng.service.CategoryService;
import com.feng.utils.BeanCopyUtil;
import com.feng.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleTagService articleTagService;

    @Autowired
    private TagMapper tagMapper;


    @Override
    public ResponseResult hotArticleList() {
        //设置查询条件
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper();

        //已发布的
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);

        //按浏览量降序排列
        queryWrapper.orderByDesc(Article::getViewCount);

        //查询前十条
        IPage<Article> page = new Page(1, 10);
        page(page, queryWrapper);
        List<Article> records = page.getRecords();

        List<Article> articles = records.stream()
                .parallel()
                .map(article -> {
                    Integer articleValue = redisCache
                            .getCacheMapValue(SystemConstants.REDIS_VIEW_COUNT_KET,
                                    article.getId().toString());
                    article.setViewCount(articleValue.longValue());
                    return article;
                })
                .collect(Collectors.toList());

        //vo转换
        List<HotArticleVo> articleVos = BeanCopyUtil.articleListVo(articles, HotArticleVo.class);
        ResponseResult result = ResponseResult.okResult(articleVos);
        return result;
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //设置查询条件
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper();

        //categoryId可能为空，如果有就要查询分类是否相同
        queryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0, Article::getCategoryId, categoryId);

        //文章必须是发布了的
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);

        //按是否置顶降序
        queryWrapper.orderByDesc(Article::getIsTop);

        //分页查询
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);

        List<Article> articles = page.getRecords();
        articles.stream()
                .map(article -> {
                    article.setCategoryName(categoryService.getById(article.getCategoryId()).getName());
                    Integer articleValue = redisCache.getCacheMapValue(SystemConstants.REDIS_VIEW_COUNT_KET, article.getId().toString());
                    article.setViewCount(articleValue.longValue());
                    return article;
                })
                .collect(Collectors.toList());

        //vo封装 这里的page.getRecords()和articles的地址值一样所以可以直接用
        List<ArticleListVo> articleListVos = BeanCopyUtil.articleListVo(page.getRecords(), ArticleListVo.class);

        ArticleListPageVo pageVo = new ArticleListPageVo(articleListVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult articleDetail(Long id) {
        //查询文章列表
        Article article = getById(id);

        Integer viewCount = redisCache.getCacheMapValue(SystemConstants.REDIS_VIEW_COUNT_KET, id.toString());
        article.setViewCount(viewCount.longValue());

        //封装VO
        ArticleDetailVo articleDetailVo = BeanCopyUtil.articleVo(article, ArticleDetailVo.class);

        //用id去分类列表中查找分类名
        Category category = categoryService.getById(article.getCategoryId());
        articleDetailVo.setCategoryName(category.getName());

        //返回
        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        redisCache.setIncrementCacheMapValue(SystemConstants.REDIS_VIEW_COUNT_KET, id.toString(), 1);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult addArticle(AddArticleDto addArticleDto) {
        Article article = BeanCopyUtil.articleVo(addArticleDto, Article.class);
        save(article);
        if(!addArticleDto.getTags().isEmpty()){
            List<ArticleTag> articleTags = addArticleDto.getTags().stream().parallel()
                    .map(tagId -> new ArticleTag(article.getId(), tagId))
                    .collect(Collectors.toList());
            articleTagService.saveBatch(articleTags);
        }
        redisCache.setCacheMapValue(SystemConstants.REDIS_VIEW_COUNT_KET, article.getId().toString(),0);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult selectList(Integer pageNum, Integer pageSize, String title, String summary) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(title), Article::getTitle, title);
        wrapper.like(StringUtils.hasText(summary), Article::getSummary, summary);
        Page<Article> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        page(page,wrapper);
        List<AdminArticleListVo> adminArticleListVos = BeanCopyUtil.articleListVo(page.getRecords(), AdminArticleListVo.class);
        return ResponseResult.okResult(new ArticleListPageVo(adminArticleListVos, page.getTotal()));
    }

    @Transactional
    @Override
    public ResponseResult getList(Long id) {
        Article article = getById(id);
        AdminUpdateGetArticleVo articleVo = BeanCopyUtil.articleVo(article, AdminUpdateGetArticleVo.class);
        List<Long> tag = tagMapper.getArticleTagById(id);
        articleVo.setTags(tag);
        return ResponseResult.okResult(articleVo);
    }

    @Transactional
    @Override
    public ResponseResult updateArticle(AdminUpdateGetArticleDto articleDto) {
        Article article = BeanCopyUtil.articleVo(articleDto, Article.class);
        updateById(article);
        if(!articleDto.getTags().isEmpty()){
            List<ArticleTag> tags = articleDto.getTags().stream().parallel()
                    .map(tagId -> new ArticleTag(articleDto.getId(), tagId))
                    .collect(Collectors.toList());
            articleTagService.updateBatchById(tags);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult deleteArticle(List<Long> idList) {
        if(idList.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.OPTION_NOT_NULL);
        }
        getBaseMapper().deleteBatchIds(idList);
        for (Long id: idList) {
            redisCache.delCacheMapValue(SystemConstants.REDIS_VIEW_COUNT_KET, id.toString());
        }
        return ResponseResult.okResult();
    }
}